package com.zjdiepu.www.biz.dh;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.AuditListStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.InsteadPaymentStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.MessageEventType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.biz.helper.ServiceHelper;
import com.zjdiepu.www.dao.dh.DhInsteadPaymentApplyMapper;
import com.zjdiepu.www.dao.dh.DhInsteadPaymentMapper;
import com.zjdiepu.www.dao.fk.FkAuditListMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.base.IDpBaseDealerInfoService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.dh.IDhInsteadPaymentApplyService;
import com.zjdiepu.www.ibiz.system.IBaseBusiUnitService;
import com.zjdiepu.www.ibiz.system.IBaseSalersmanService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.model.base.dto.DpBaseDealerInfo;
import com.zjdiepu.www.model.dh.dto.DhInsteadPayment;
import com.zjdiepu.www.model.dh.dto.DhInsteadPaymentApply;
import com.zjdiepu.www.model.dh.ext.DhInsteadPaymentApplyExt;
import com.zjdiepu.www.model.dh.vo.DhInsteadPaymentApplyVo;
import com.zjdiepu.www.model.fk.dto.FkAuditList;
import com.zjdiepu.www.model.fk.ext.FkAuditListExt;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * Service层操作实现<br/>
 * @author zhangzhengjian<br/>
 * @time 2017年05月22日 20时55分<br/>
 * @since 1.0<br/>
 */
@Service
public class DhInsteadPaymentApplyServiceImpl extends BaseService implements IDhInsteadPaymentApplyService {
	public static final Logger logger = LoggerFactory.getLogger(DhInsteadPaymentApplyServiceImpl.class);

	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private DhInsteadPaymentApplyMapper dhInsteadPaymentApplyMapper;
	@Autowired
    private ServiceHelper serviceHelper;
	@Autowired
	private SystemService systemService;
	@Autowired
	private DhInsteadPaymentMapper dhInsteadPaymentMapper;
	@Autowired
	private FkAuditListMapper fkAuditListMapper;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
    private IBaseSalersmanService baseSalersmanService;
    @Resource
    private IBaseBusiUnitService baseBusiUnitService;
    @Resource
    private IDpBaseDealerInfoService baseDealerInfoService;
	@Override
	public void saveUpdateAndDelete(AbstractSysUser currentUser,DhInsteadPaymentApply dhInsteadPaymentApply, OperateType operType) {
		switch (operType) {
		case add:
			dhInsteadPaymentApply.initInsertData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
			dhInsteadPaymentApplyMapper.insert(dhInsteadPaymentApply);
	        String busiId = dhInsteadPaymentApply.getBusiId();
	        if(StringUtils.isBlank(busiId)) {
	        	ExceptionHelper.thow("999", "业务ID为空");
	        }
	        try {
				systemService.diepuNewsHandle(currentUser, ModeIDType.CWDK.getCode(), MessageEventType.CWDKTZ.getCode(), busiId, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case edit:
			dhInsteadPaymentApply.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
			// 影响的记录数
			int updateCount = dhInsteadPaymentApplyMapper.updateByPrimaryKeySelective(dhInsteadPaymentApply);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dhInsteadPaymentApply.initDeleteData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
			// 影响的记录数
			int deleteCount = dhInsteadPaymentApplyMapper.updateByPrimaryKeySelective(dhInsteadPaymentApply);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<DhInsteadPaymentApply> selectByExt(DhInsteadPaymentApplyExt dhInsteadPaymentApplyExt) {
		return dhInsteadPaymentApplyMapper.selectByExt(dhInsteadPaymentApplyExt);
	}
	
	@Override
	public int countByExt(DhInsteadPaymentApplyExt dhInsteadPaymentApplyExt){
		return dhInsteadPaymentApplyMapper.countByExt(dhInsteadPaymentApplyExt);
	}
	
	@Override
	public DhInsteadPaymentApply selectById(String id) {
		return dhInsteadPaymentApplyMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dhInsteadPaymentApplyMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DhInsteadPaymentApply dhInsteadPaymentApply) {
		return dhInsteadPaymentApplyMapper.countRefined(dhInsteadPaymentApply);
	}

	@Override
	public DhInsteadPaymentApply selectRefined(DhInsteadPaymentApply dhInsteadPaymentApply) {
		return dhInsteadPaymentApplyMapper.selectRefined(dhInsteadPaymentApply);
	}

	@Override
	public boolean repeat(DhInsteadPaymentApply dhInsteadPaymentApply) {
		int count = countRefined(dhInsteadPaymentApply);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dhInsteadPaymentApply.getId())) {
			return true;
		}
		DhInsteadPaymentApply dbItem = selectRefined(dhInsteadPaymentApply);
		if(null == dbItem) {
			return false;
		}
		return !dhInsteadPaymentApply.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dhInsteadPaymentApplyMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}

	@Override
	public int countMultiByExt(YwBusinessQueryRequest ywBusinessQueryRequest) {
		return dhInsteadPaymentApplyMapper.countMultiByExt(ywBusinessQueryRequest);
	}

	@Override
	public List<DhInsteadPaymentApplyVo> selectMultiByExt(
			YwBusinessQueryRequest ywBusinessQueryRequest) {
		return dhInsteadPaymentApplyMapper.selectMultiByExt(ywBusinessQueryRequest);
	}

	@Override
	public void revokeInsteadPayment(DhInsteadPaymentApply dhInsteadPaymentApply,AbstractSysUser currentUser) {
		Integer statusInstead=dhInsteadPaymentApply.getStatusInstead();
		if(statusInstead!=null && statusInstead==InsteadPaymentStatus.YESREMIT.getCode()){
			throw new BaseException(ResultFlagType.DAI_CHANG_YI_TI_JIAO.getCode().toString(),ResultFlagType.DAI_CHANG_YI_TI_JIAO.getValue());
		}
		//将“dh_待垫资打款申请”的“代垫资打款状态”更改为“已撤回”；
		DhInsteadPaymentApply dhInsteadPaymentApply1=new DhInsteadPaymentApply();
		dhInsteadPaymentApply1.setBusiId(dhInsteadPaymentApply.getBusiId());
		dhInsteadPaymentApply1=dhInsteadPaymentApplyMapper.selectRefined(dhInsteadPaymentApply1);
		if(dhInsteadPaymentApply1!=null){
			dhInsteadPaymentApply1.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
			dhInsteadPaymentApply1.setStatusInstead(InsteadPaymentStatus.YESREVOKE.getCode());
			dhInsteadPaymentApplyMapper.updateByPrimaryKeySelective(dhInsteadPaymentApply1);
		}
		//将“dh_待垫资打款”的“代垫资打款状态”修改为“已撤回”；
		DhInsteadPayment dhInsteadPayment=new DhInsteadPayment();
		dhInsteadPayment.setDpStatus(DpStatus.NORMAL.getCode());
		dhInsteadPayment.setBusiId(dhInsteadPaymentApply.getBusiId());
		dhInsteadPayment=dhInsteadPaymentMapper.selectRefined(dhInsteadPayment);
		if(dhInsteadPayment!=null){
			dhInsteadPayment.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
			dhInsteadPayment.setStatusInstead(InsteadPaymentStatus.YESREVOKE.getCode());
			dhInsteadPaymentMapper.updateByPrimaryKeySelective(dhInsteadPayment);
		}
		//如果ModeID为代偿稽核审查（M_dcjhsc）的待审核数据未审批，将该数据设置为无效；
		FkAuditListExt fkAuditListExt=new FkAuditListExt();
		fkAuditListExt.setBusiId(dhInsteadPaymentApply.getBusiId());
		fkAuditListExt.setModeId(ModeIDType.DCHJHSHCH.getCode());
		List<FkAuditList> list=fkAuditListMapper.selectByExt(fkAuditListExt);
		for (FkAuditList fkAuditList : list) {
			if(fkAuditList!=null && fkAuditList.getAuditListStatus()==AuditListStatus.WEI_SHEN_PI.getCode()){
				fkAuditList.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
				fkAuditList.setDpStatus(DpStatus.INVALID.getCode());
				fkAuditListMapper.updateByPrimaryKeySelective(fkAuditList);
			}
		}
	}

	@Override
	public void saveAll(DhInsteadPaymentApply dhInsteadPaymentApply,
			AbstractSysUser currentUser) {
		Integer statusInstead=dhInsteadPaymentApply.getStatusInstead();
    	if(statusInstead!=null && statusInstead==InsteadPaymentStatus.YESREVOKE.getCode()){
    		 ApiResponse.fail(ResultFlagType.DAI_CHANG_YI_TI_JIAO);
    	}
    	dhInsteadPaymentApply.initInsertData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
    	dhInsteadPaymentApplyMapper.insert(dhInsteadPaymentApply);
        
    	
        DhInsteadPayment dhInsteadPayment=new DhInsteadPayment();
        dhInsteadPayment.setId(dhInsteadPaymentApply.getInsteadId());
        dhInsteadPayment.setStatusInstead(InsteadPaymentStatus.YESAPPLY.getCode());
        dhInsteadPayment.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
        dhInsteadPaymentMapper.updateByPrimaryKeySelective(dhInsteadPayment);
    	
    	FkAuditList fkAuditList= new FkAuditList();
    	fkAuditList.setBusiId(dhInsteadPaymentApply.getBusiId());
    	fkAuditList.setModeId(ModeIDType.DCHJHSHCH.getCode());
    	fkAuditList.setSource("代偿申请");
    	YwBusiness ywbusiness=ywBusinessMapper.selectByPrimaryKey(dhInsteadPaymentApply.getBusiId());
    	if(ywbusiness!=null){
    		fkAuditList.setBusiConfirmTime(ywbusiness.getSubmitTime());
    		fkAuditList.setLoanAmount(ywbusiness.getSignLoanAmount());
    		fkAuditList.setChannelType(ywbusiness.getChannelType());
    		fkAuditList.setChannelTypeName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelType()), DataDicType.CHANNEL_TYPE));
    		fkAuditList.setChannelStatus(ywbusiness.getChannelStatus());
    		fkAuditList.setChannelStatusName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelStatus()), DataDicType.CHANNEL_STATUS));
    		fkAuditList.setDealer(ywbusiness.getDealerId());
			BaseSalersman baseSalersman=baseSalersmanService.selectById(ywbusiness.getSalesmanId());
			if(baseSalersman!=null && baseSalersman.getUnitId()!=null){
				fkAuditList.setSalersmanName(baseSalersman.getName());
				BaseBusiUnit baseBusiUnit=baseBusiUnitService.selectById(baseSalersman.getUnitId());
				if(baseBusiUnit !=null){
					fkAuditList.setDepartmentName(baseBusiUnit.getOrgName());
				}
			}
    		DpBaseDealerInfo baseDealerInfo=baseDealerInfoService.selectById(ywbusiness.getDealerId());
    		if(baseDealerInfo!=null){
    			fkAuditList.setDealer(baseDealerInfo.getDealerName());
    		}
    		fkAuditList.setCusName(ywbusiness.getCustomerName());
    		fkAuditList.setCusIdno(ywbusiness.getCustomerNo());
    		fkAuditList.setBankname(cachedDictionaryService.getName(ywbusiness.getBankLoan(),DataDicType.LOAN_BANK));
    		fkAuditList.setStatusList(1);
    	}
    	fkAuditList.initInsertData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
    	fkAuditListMapper.insert(fkAuditList);
		
	}

	@Override
	public void modifyAll(DhInsteadPaymentApply dhInsteadPaymentApply) {
		dhInsteadPaymentApply.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
		dhInsteadPaymentApplyMapper.updateByPrimaryKeySelective(dhInsteadPaymentApply);
		
		DhInsteadPayment dhInsteadPayment=new DhInsteadPayment();
        dhInsteadPayment.setId(dhInsteadPaymentApply.getInsteadId());
        dhInsteadPayment.setStatusInstead(InsteadPaymentStatus.YESAPPLY.getCode());
        dhInsteadPayment.initUpdateData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
        dhInsteadPaymentMapper.updateByPrimaryKeySelective(dhInsteadPayment);
		
        
        FkAuditList fkAuditList= new FkAuditList();
    	fkAuditList.setBusiId(dhInsteadPaymentApply.getBusiId());
    	fkAuditList.setModeId(ModeIDType.DCHJHSHCH.getCode());
    	fkAuditList.setSource("代偿申请");
    	YwBusiness ywbusiness=ywBusinessMapper.selectByPrimaryKey(dhInsteadPaymentApply.getBusiId());
    	if(ywbusiness!=null){
    		fkAuditList.setBusiConfirmTime(ywbusiness.getSubmitTime());
    		fkAuditList.setLoanAmount(ywbusiness.getSignLoanAmount());
    		fkAuditList.setChannelType(ywbusiness.getChannelType());
    		fkAuditList.setChannelTypeName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelType()), DataDicType.CHANNEL_TYPE));
    		fkAuditList.setChannelStatus(ywbusiness.getChannelStatus());
    		fkAuditList.setChannelStatusName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelStatus()), DataDicType.CHANNEL_STATUS));
    		fkAuditList.setDealer(ywbusiness.getDealerId());
			BaseSalersman baseSalersman=baseSalersmanService.selectById(ywbusiness.getSalesmanId());
			if(baseSalersman!=null && baseSalersman.getUnitId()!=null){
				fkAuditList.setSalersmanName(baseSalersman.getName());
				BaseBusiUnit baseBusiUnit=baseBusiUnitService.selectById(baseSalersman.getUnitId());
				if(baseBusiUnit !=null){
					fkAuditList.setDepartmentName(baseBusiUnit.getOrgName());
				}
			}
    		DpBaseDealerInfo baseDealerInfo=baseDealerInfoService.selectById(ywbusiness.getDealerId());
    		if(baseDealerInfo!=null){
    			fkAuditList.setDealer(baseDealerInfo.getDealerName());
    		}
    		fkAuditList.setCusName(ywbusiness.getCustomerName());
    		fkAuditList.setCusIdno(ywbusiness.getCustomerNo());
    		fkAuditList.setBankname(cachedDictionaryService.getName(ywbusiness.getBankLoan(),DataDicType.LOAN_BANK));
    		fkAuditList.setStatusList(1);
    	}
    	fkAuditList.initInsertData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
    	fkAuditListMapper.insert(fkAuditList);
        
//        FkAuditList fkAuditList= new FkAuditList();
//    	fkAuditList.setBusiId(dhInsteadPaymentApply.getBusiId());
//    	fkAuditList.setModeId(ModeIDType.DCHJHSHCH.getCode());
//    	fkAuditList=fkAuditListMapper.selectRefined(fkAuditList);
//    	if(fkAuditList!=null){
//    		fkAuditList.initInsertData(dhInsteadPaymentApply.getModifier(), dhInsteadPaymentApply.getModifierName());
//    		fkAuditListMapper.insert(fkAuditList);
//    	}
	}
}
